package util;

import org.apache.http.client.ClientProtocolException;

import java.io.*;
import java.net.*;
import java.util.Map;

/**
 * Created by Administrator on 2016/3/7.
 */
public class HttpUtil {
    public static final int GET = 0;
    public static final int POST = 1;
    public static final int PUT = 2;
    public static final int HEAD = 3;
    public static final int OPTION = 4;
    public static final int DELETE = 5;

    public static InputStream get(String url) throws IOException {
        return get(url, null);
    }

    public static InputStream get(String url, Map<String, String> headers) throws IOException {
        URL urlObj = new URL(url);
        HttpURLConnection  conn = (HttpURLConnection )urlObj.openConnection();
        if (headers != null) {
            for (String key : headers.keySet()) {
                conn.setRequestProperty(key, headers.get(key));
            }
        }
        conn.setRequestProperty("Accept-Charset", "utf-8");
        conn.connect();
        if(conn.getResponseCode()!=200){
            return null;
        }
        return conn.getInputStream();
    }

    public static InputStream post(String url, String body) throws IOException {
        InputStream inputStream = body != null ? DataFormatUtil.createInputStreamFromString(body, "UTF-8") : null;
        return post(url, inputStream);
    }

    public static InputStream post(String url, InputStream inputStream) throws IOException {
        return post(url, inputStream, null);
    }

    public static InputStream post(String url, InputStream inputStream, Map<String, String> headers) throws IOException {
        URL urlObj = new URL(url);
        URLConnection conn = urlObj.openConnection();
        if (headers != null) {
            for (String key : headers.keySet()) {
                conn.setRequestProperty(key, headers.get(key));
            }
        }
        conn.setDoOutput(true);
        if (inputStream != null) {
            conn.getOutputStream().write(DataFormatUtil.fullyReadStreamToBytes(inputStream));
        }
        conn.connect();
        return conn.getInputStream();
    }
}
